package com.server.userCenter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.config.AppReturn;
import com.config.ConstDefine;
import com.server.user.UserDAO;
import com.util.IOUtil;
import com.util.StrKit;

/**
 * 奖励UTIL
 * @author dell
 *
 */
@Component
public class RewardUtil {

	@Autowired
	UserCenterDAO ucDao;
	@Autowired
	UserDAO uDao;
	@Autowired
	RewardDAO rewardDao;
	
	/**
	 * 处理礼券
	 * @param list
	 */
	public void lq(Map<String, Object> list)
	{
		if(!list.get("status").equals("2")&&!list.get("status").equals("3"))return ;//判断付款状态
		if(list.get("ifreward_lq").equals("1"))return ;//判断是否已经处理礼券
		String listid = list.get("id").toString();
		String userid=list.get("userid").toString();  
		//查询礼券
		Map<String, Object> lqData = rewardDao.getListLq(listid);
		int lq = (int)(((BigDecimal) lqData.get("s")).doubleValue());
		
		//更新用户信息
		if(lq>0)
		{
			ucDao.upUserAmount(userid, 0, 0, lq);
			ucDao.insLQLog(IOUtil.getId(), userid, "1", lq+"", "22", "", listid);
		}
		
		//更新订单状态ifreward_lq状态，防止重复分润
		Map<String, Object> upListMap = new HashMap<String, Object>();
		upListMap.put("ifreward_lq", "1");
		upListMap.put("id", listid);
		ucDao.upList(upListMap);		
		
	}
	
	/**
	 * 处理上个月艾豆
	 */
	public void doAd()
	{
		//获取所有用户
		List<Map<String, Object>> userAll = ucDao.getAllUser();

		//保存有分红的用户
		List<Map<String, Object>> userIns = new ArrayList<Map<String,Object>>();
		
		double pvAll = 0;//全体人员的总贡献
		String month = IOUtil.getLastMonth();
		//先计算总贡献
		for(int i=0;i<userAll.size();i++)
		{
			Map<String, Object> user = userAll.get(i);
			double ad = userAd(user);
			pvAll=pvAll+ad;
			if(ad>0){
				user.put("ad_value", ad); 
				userIns.add(user);
			}
		}
		//循环处理每个用户
		if(userIns!=null&&userIns.size()>0)
		{
			for(int i=0;i<userIns.size();i++)
			{
				Map<String, Object> user = userIns.get(i);
				double ad_value = (double) user.get("ad_value");
				user.put("type", "1");
				user.put("ad", (int)(ad_value/pvAll*ConstDefine.getAdMonth()));
				user.put("log_amount", (int)(ad_value/pvAll*ConstDefine.getAdMonth()));
				user.put("month", month);
				user.put("operation", ConstDefine.AD);
			}  
			//跟新艾豆，插入记录 
			ucDao.upUserADList(userIns);
			ucDao.insAdLogList(userIns);
			rewardDao.insRewardMonthLogList(userIns);
		}
		
	}
	
	/**
	 * 计算该用户上个月应得的艾豆
	 * @param list
	 */
	public double userAd(Map<String, Object> user)
	{
		String userid = (String)user.get("id");
		String stime = IOUtil.getLastMonth()+"-01";//上月第一天
		String etime = IOUtil.getdate("yyyy-MM")+"-01";//本月第一天
		//判断是否已经有记录。如果有则结束，防止重复操作
		String month = IOUtil.getLastMonth();
		Map<String, Object> rewardLog = rewardDao.getRewardMonthLog(month, userid, ConstDefine.AD);
		if(rewardLog!=null&&rewardLog.containsKey("id"))return 0;
		
		//获取上个月的PV
		Map<String, Object> userPVMap = rewardDao.getUserPV(userid, stime, etime);
		double userPV = ((BigDecimal) userPVMap.get("spv")).doubleValue();
		//获取上个月的奖金
		String typein = "('"+ConstDefine.INCOME_DIRECT+"','"+ConstDefine.INCOME_LEVEL+"','"+ConstDefine.INCOME_EQUAL+"')";
		Map<String, Object> rewardMap = rewardDao.countRewardMonth(month, userid, typein);
		double rewardPV = ((BigDecimal) rewardMap.get("samount")).doubleValue();
		
		//获取艾豆
		double ad = userPV*6+rewardPV*9;
		return ad; 
	}
	/**
	 * 处理该用户上个月直推奖
	 * @param user
	 */
	public void directAmount(Map<String, Object> user)
	{
		String userid = (String)user.get("id");

		//判断是否已经有记录。如果有则结束，防止重复操作
		String month = IOUtil.getLastMonth();
		Map<String, Object> rewardLog = rewardDao.getRewardMonthLog(month, userid, ConstDefine.INCOME_DIRECT);
		if(rewardLog!=null&&rewardLog.containsKey("id"))return;
		
		int conditionNum = 0;//记录满足条件的小组数
		String stime = IOUtil.getLastMonth()+"-01";//上月第一天
		String etime = IOUtil.getdate("yyyy-MM")+"-01";//本月第一天
		int pointNum = ConstDefine.getPointNum();
		//查询该用户所有直推用户
		List<Map<String, Object>> directUser = rewardDao.getDirectUser(userid);
		//计算每个直推小组的历史总PV,如果满足大于499，计数
		if(directUser!=null&&directUser.size()>0)
		{
			for(int i =0 ;i<directUser.size();i++)
			{
				Map<String, Object> duser = directUser.get(i);
				Map<String, Object> pv = rewardDao.getTeamPV(duser.get("id").toString(), null, etime);//查询到本月第一天为止的历史PV
				BigDecimal bigNum = (BigDecimal) pv.get("spv");
				if(bigNum.intValue()>=pointNum)conditionNum++;
			}
		}
		//计算本人本月应得PV
		if(conditionNum>0)
		{
			//查询上个月的总PV
			Map<String, Object> myPV = rewardDao.getUserPV(userid, stime, etime);
			BigDecimal bigNum = (BigDecimal) myPV.get("spv");
			int userPV = bigNum.intValue();//上个月总PV
			double percent = 0;//百分比
			//判断百分比
			if(conditionNum>=1&&conditionNum<=3)percent=0.1;
			else if(conditionNum>=4&&conditionNum<=14)percent=0.15;
			else if(conditionNum>=15)percent=0.2;
			double total = userPV*percent;
			//插入记录
			rewardDao.insRewardMonthLog(month, userid, ConstDefine.INCOME_DIRECT, total);
			//更新用户金额
			ucDao.upUserAmount(userid, total, 0, 0);
			//插入交易记录
			ucDao.insAmountLog(IOUtil.getId(), userid, "1", total, ConstDefine.INCOME_DIRECT, "", "");
		}
	}
	/**
	 * 用户上个月极差奖+平级奖
	 * @param user
	 */
	public void levelAmount()
	{
		//获取所有用户
		List<Map<String, Object>> userAll = ucDao.getAllUser();
		//存储所有可以获得极差奖的用户
		List<Map<String, Object>> amountUser = new ArrayList<Map<String,Object>>();
		//存储所有获取平级奖的用户
		List<Map<String, Object>> equalUser = new ArrayList<Map<String,Object>>();
		//存储所有极差奖为0的用户
		List<Map<String, Object>> noAmountUser = new ArrayList<Map<String,Object>>();

		String month = IOUtil.getLastMonth();
		//循环每个用户
		for(int a = 0 ;a<userAll.size();a++)
		{
			Map<String, Object> user = userAll.get(a);
			String userid = (String)user.get("id");
			String stime = IOUtil.getLastMonth()+"-01";//上月第一天
			String etime = IOUtil.getdate("yyyy-MM")+"-01";//本月第一天
			//判断是否已经有记录。如果有则结束，防止重复操作
			Map<String, Object> rewardLog = rewardDao.getRewardMonthLog(month, userid, ConstDefine.INCOME_LEVEL);
			if(rewardLog!=null&&rewardLog.containsKey("id"))continue;
			
			
			//获取本团队上个月PV
			Map<String, Object> pvMap_all = rewardDao.getTeamPV(userid, stime, etime);//查询到本月第一天为止的历史PV
			double pv_all =  ((BigDecimal) pvMap_all.get("spv")).doubleValue();//本团队所有PV
			double pv_allAmount = pv_all*getLevelPercent(pv_all);//本团队总共能得到的钱
			double pv_teamAll = 0;//下属所有团队能得到的总钱
			
			//获取每个小组上个月PV
			//查询该用户所有直推用户
			List<Map<String, Object>> directUser = rewardDao.getDirectUser(userid);
			//计算每个直推小组的PV
			if(directUser!=null&&directUser.size()>0)
			{
				for(int i =0 ;i<directUser.size();i++)
				{
					Map<String, Object> duser = directUser.get(i);
					Map<String, Object> pv = rewardDao.getTeamPV(duser.get("id").toString(), stime, etime);//查询到本月第一天为止的历史PV
					double teamPv = ((BigDecimal) pv.get("spv")).doubleValue();
					pv_teamAll=pv_teamAll+teamPv*getLevelPercent(teamPv);
				}
			}
			//求差
			double levelAmount = pv_allAmount-pv_teamAll;
			//如果大于0，加入有极差奖的list
			if(levelAmount>0)
			{
				user.put("log_amount", levelAmount);
				user.put("type", "1");
				user.put("month", month);
				user.put("operation", ConstDefine.INCOME_LEVEL);
				amountUser.add(user);	
			}else{//如果=0，加入没有极差奖的list
				noAmountUser.add(user);
			}
		}
		
		//循环amountUser，判断里面的用户，如果其上级用户没有PV，则给他们10%的平级奖
		if(amountUser!=null&&amountUser.size()>0&&noAmountUser!=null&&noAmountUser.size()>0)
		{
			for(int i = 0 ;i<amountUser.size();i++)
			{
				Map<String, Object> user = amountUser.get(i);
				//判断上级用户是否在noAmountUser，如果是，则代表有平级将
				String tjrcode = user.get("tjrcode").toString();
				if(StrKit.notBlank(tjrcode))
				{
					for(int m=0;m<noAmountUser.size();m++)
					{
						Map<String, Object> user_noAmount = noAmountUser.get(m);
						if(user_noAmount.get("tjcode")!=null&&user_noAmount.get("tjcode").equals(tjrcode))
						{
							//符合平级奖
							//修改原用户金额
							user.put("log_amount", (double)user.get("log_amount")*0.9);
							//给上级用户分平级奖
							user_noAmount.put("log_amount", (double)user.get("log_amount")*0.1);
							user_noAmount.put("operation", ConstDefine.INCOME_EQUAL);
							user_noAmount.put("type", "1");
							user_noAmount.put("month", month);
							equalUser.add(user_noAmount);
							break;
						}
					}
				}
			}
		}
		//循环处理amountUser
		ucDao.insAmountLogList(amountUser);
		ucDao.upAmountList(amountUser);
		rewardDao.insRewardMonthLogList(amountUser);
		
		//循环处理equalUser
		ucDao.insAmountLogList(equalUser);
		ucDao.upAmountList(amountUser);
		rewardDao.insRewardMonthLogList(amountUser);
		
	}
	/**
	 * 根据PV，获取极差奖的百分比
	 * @param pv
	 * @return
	 */
	public double getLevelPercent(double pv)
	{
		double res = 0;
		if(pv>499&&pv<6000)res=0.09;
		else if(pv>=6000&&pv<12000)res=0.12;
		else if(pv>=12000&&pv<20000)res=0.15;
		else if(pv>=20000&&pv<28000)res=0.18;
		else if(pv>=28000&&pv<56000)res=0.21;
		else if(pv>=56000&&pv<100000)res=0.23;
		else if(pv>=100000&&pv<300000)res=0.25;
		else if(pv>=300000&&pv<800000)res=0.27;
		else if(pv>=800000&&pv<2000000)res=0.29;
		else if(pv>=2000000&&pv<5000000)res=0.31;
		else if(pv>=5000000&&pv<12000000)res=0.33;
		else if(pv>=12000000)res=0.35;
		return res;
	}
	
	
	/**
	 * 将#分割的字符串转成（‘’，‘’）形式
	 * @param Str
	 * @return
	 */
	public String splite2Strl(String str)
	{
		if(StrKit.notBlank(str))
		{
			StringBuffer sb = new StringBuffer("(");
		
			String[] strArr=str.split("#");
			for(int i=0;i<strArr.length;i++)
			{
				if(i!=0)sb.append(",");
				sb.append("'").append(strArr[i].trim()).append("'");
			}
			sb.append(")");
			return sb.toString();
		}
		else{
			return "('')";
		}
	}
	
	/**
	 * 获取该订单的商品数量。暂时按照/599计算
	 * @param list
	 * @return
	 */
	public int getGoodsNum(Map<String, Object> list)
	{
		double amount = (Double)list.get("reward_amount");
		return (int)amount/599;
	}
	
	/**
	 * 根据金额，返回按月分红的级别
	 * @param amount
	 * @return
	 */
	public int getAmountLevel(double amount)
	{
		//这里用钱计算。所以金额*599
		amount=amount*599;
		int level = 1;
		if(amount>=20*10000&&amount<50*10000)level=2;
		else if(amount>=50*10000&&amount<90*10000)level=3;
		else if(amount>=90*10000&&amount<130*10000)level=4;
		else if(amount>=130*10000&&amount<180*10000)level=5;
		else if(amount>=180*10000&&amount<240*10000)level=6;
		else if(amount>=240*10000&&amount<300*10000)level=7;
		else if(amount>=300*10000&&amount<370*10000)level=8;
		else if(amount>=370*10000&&amount<450*10000)level=9;
		else if(amount>=450*10000)level=10;
		
		return level;
	}
	/**
	 * 查询小部门的总金额
	 * @param user
	 * @return
	 */
	public double getSmaTeam(Map<String, Object> user)
	{
//		System.out.println("处理用户："+user.get("phone"));
		double res = 0;
		//获取所有下级用户
		List<Map<String, Object>> directUserList = ucDao.getDirectUser(user.get("tjcode").toString());
		if(directUserList!=null&&directUserList.size()>0)
		{
			double[] amountArr = new double[directUserList.size()];
			//计算直属用户每个人的团队金额
			for(int i=0;i<directUserList.size();i++)
			{
				Map<String, Object> directUser = directUserList.get(i);
				double teamAmount = (Double)(ucDao.countTeamSell(getSelfTjtree(directUser),directUser.get("id").toString()).get("su"));//全部团队的销售额
				amountArr[i]=teamAmount;
//				System.out.println(directUser.get("phone")+"个部门单数："+amountArr[i]);
			}
			Arrays.sort(amountArr);//重新排序
			for(int i=0;i<amountArr.length-1;i++)//不算最后一条，把所有部门的金额加起来
			{
				res=res+amountArr[i];
			}
			
		}
//		System.out.println(user.get("phone")+" 小部门单数："+res);
//		System.out.println("处理结束");
		return res;
	}
	/**
	 * 拼装自己查询上级时用到的推荐树
	 * @param user
	 * @return
	 */
	public String getSelfTjtree(Map<String, Object> user)
	{
		if(user.get("tjtree")!=null&&StrKit.notBlank(user.get("tjtree").toString()))
		{
			return user.get("tjtree").toString()+"#"+user.get("tjcode").toString();
		}else{
			return user.get("tjcode").toString();
		}
		
	}
}
